package com.cqc.appmanager01;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cqc.appmanager01.utils.LogUtil;
import com.cqc.appmanager01.utils.ToastUtil;
import com.stericson.RootTools.RootTools;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;
import opensource.jpinyin.PinyinFormat;
import opensource.jpinyin.PinyinHelper;

/**
 * 1 获取手机和sd卡可用空间
 * 2 获取手机中安装的app，并区分哪些是系统应用，哪些是用户安装
 * 3 listView的复杂显示
 */
public class MainActivity extends AppCompatActivity {

    private Context context = this;
    private List<AppInfo> appList = new ArrayList<>();
    private List<AppInfo> sysAppList = new ArrayList<>();
    private List<AppInfo> userAppList = new ArrayList<>();

    @BindView(R.id.layout_loading)
    LinearLayout layoutLoading;
    @BindView(R.id.tv_phone_size)
    TextView tvPhoneSize;
    @BindView(R.id.tv_sd_size)
    TextView tvSdSize;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.layout_content)
    LinearLayout layoutContent;
    @BindView(R.id.tv_up_case)
    TextView tvUpCase;
    private TextView tvUninstallApp;
    private TextView tvStartApp;
    private TextView tvShareApp;
    private TextView tvSettingApp;
    //    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSize();//获取手机和sd卡剩余空间

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                layoutContent.setVisibility(View.GONE);
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                getAppsList();
                for (AppInfo appInfo : appList) {
                    if (appInfo.isSys()) {
                        sysAppList.add(appInfo);
                    } else {
                        userAppList.add(appInfo);
                    }
                }

                Comparator<AppInfo> comparator = new Comparator<AppInfo>() {
                    @Override
                    public int compare(AppInfo o1, AppInfo o2) {
                        String s1 = PinyinHelper.convertToPinyinString(o1.getLabel(), "", PinyinFormat.WITHOUT_TONE).toUpperCase();
                        String s2 = PinyinHelper.convertToPinyinString(o2.getLabel(), "", PinyinFormat.WITHOUT_TONE).toUpperCase();
                        return s1.compareTo(s2);
                    }
                };
                Collections.sort(sysAppList, comparator);
                Collections.sort(userAppList, comparator);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                layoutLoading.setVisibility(View.GONE);
                layoutContent.setVisibility(View.VISIBLE);

                MyAdapter adapter = new MyAdapter(sysAppList, userAppList);
                listView.setAdapter(adapter);
            }
        }.execute();

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {//AbsListView.OnScrollListener
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                LogUtil.d("scrollState=" + scrollState);
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE://idle状态是隐藏
                        //                        tvUpCase.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //当然也可可以反放在case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:中判断
                if (firstVisibleItem > 0 && firstVisibleItem < (userAppList.size() + 1)) {
                    String label1 = userAppList.get(firstVisibleItem - 1).getLabel();
                    String pinyinLabel1 = PinyinHelper.convertToPinyinString(label1, "", PinyinFormat.WITHOUT_TONE);
                    String substring = pinyinLabel1.toUpperCase().substring(0, 1);

                    tvUpCase.setVisibility(View.VISIBLE);
                    tvUpCase.setText(substring);
                } else if (firstVisibleItem > userAppList.size()) {
                    String label2 = sysAppList.get(firstVisibleItem - 1 - userAppList.size()).getLabel();
                    String pinyinLabel2 = PinyinHelper.convertToPinyinString(label2, "", PinyinFormat.WITHOUT_TONE);
                    String substring2 = pinyinLabel2.toUpperCase().substring(0, 1);
                    tvUpCase.setVisibility(View.VISIBLE);
                    tvUpCase.setText(substring2);
                }

                //也可以3s后消失
                if (tvUpCase.getVisibility() == View.VISIBLE) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tvUpCase.setVisibility(View.GONE);
                        }
                    }, 3000);
                }
            }
        });

        listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0 || position != (userAppList.size() + 1)) {
                  /*
                      if (popupWindow != null) {
                            popupWindow.dismiss();
                            popupWindow = null;
                        }
                    */
                    View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.popup_window_tips, parent, false);
                    PopupWindow popupWindow = new PopupWindow(rootView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    popupWindow.setContentView(rootView);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setFocusable(true);
                    //必须给popupWindow设置BackgroundDrawable，否则setFocusable(true)无效
                    popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

                    //                if (popupWindow.isShowing()) {
                    //                    popupWindow.dismiss();
                    //                }

                    tvUninstallApp = (TextView) rootView.findViewById(R.id.tv_uninstall_app);
                    tvStartApp = (TextView) rootView.findViewById(R.id.tv_start_app);
                    tvShareApp = (TextView) rootView.findViewById(R.id.tv_share_app);
                    tvSettingApp = (TextView) rootView.findViewById(R.id.tv_setting_app);

                    AppInfo info;
                    if (position <= userAppList.size()) {
                        info = userAppList.get(position - 1);
                    } else {
                        info = sysAppList.get(position - 2 - userAppList.size());
                    }
                    MenuOnClickListener clickListener = new MenuOnClickListener(info);
                    tvUninstallApp.setOnClickListener(clickListener);
                    tvStartApp.setOnClickListener(clickListener);
                    tvShareApp.setOnClickListener(clickListener);
                    tvSettingApp.setOnClickListener(clickListener);

                    /**
                     * 2 种显示方式
                     */
                    //方式一：
                    int[] locations = new int[2];
                    view.getLocationInWindow(locations);//Gravity.TOP|Gravity.LEFT
                    popupWindow.showAtLocation(view, Gravity.TOP, locations[0], locations[1]);
                    //方式二：显示在View下方
                    popupWindow.showAsDropDown(view);
                    popupWindow.showAsDropDown(view, 100, 0);//后2个参数是x y轴偏移量

                    //                                    加入动画
                    AlphaAnimation alpha = new AlphaAnimation(0.5f, 1.0f);
                    ScaleAnimation scale = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f);

                    AnimationSet set = new AnimationSet(true);
                    set.addAnimation(alpha);
                    set.addAnimation(scale);
                    set.setDuration(1500);
                    rootView.startAnimation(set);
                }
            }
        });
    }


    private class MenuOnClickListener implements View.OnClickListener {

        AppInfo info;

        public MenuOnClickListener(AppInfo info) {
            super();
            this.info = info;
        }

        @Override
        public void onClick(View v) {
            ToastUtil.showShortToast(context, "" + v.getId());
            switch (v.getId()) {
                case R.id.tv_uninstall_app://卸载
                    if (info != null && !info.isSys()) {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.DELETE");
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.setData(Uri.parse("package:" + info.getPackageName()));
                        startActivity(intent);
                    }
                    if (info != null && info.isSys()) {
                        try {
                            if (!RootTools.isAccessGiven()) {
                                ToastUtil.showShortToast(context, "请给于root权限");
                            }
                            if (!RootTools.isRootAvailable()) {
                                ToastUtil.showShortToast(context, "请给于root权限");
                            }
                            // 在项目中一定复制
                            RootTools.sendShell("mount -o remount  ,rw /system", 3000);
                            RootTools.sendShell("rm -r " + info.getSourceDir(), 3000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case R.id.tv_start_app:
                    PackageManager pm = getPackageManager();
                    Intent launchIntent = pm.getLaunchIntentForPackage(info.getPackageName());
                    if (launchIntent != null) {
                        startActivity(launchIntent);
                    } else {
                        ToastUtil.showShortToast(context, "启动失败");
                    }
                    break;
                case R.id.tv_share_app:
                    Intent smsIntent = new Intent();
                    smsIntent.setAction("android.intent.action.SEND");
                    smsIntent.addCategory("android.intent.category.DEFAULT");
                    smsIntent.setType("text/plain");
                    smsIntent.putExtra("sms_body", "发送一条短信");
                    startActivity(smsIntent);
                    break;
                case R.id.tv_setting_app:
                    Intent setIntent = new Intent();
                    setIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    setIntent.addCategory("android.intent.category.DEFAULT");
                    setIntent.setData(Uri.parse("package:" + info.getPackageName()));
                    startActivity(setIntent);
                    break;
            }
        }

    }

    private void setSize() {
        long phoneFreeSpaceL = Environment.getDataDirectory().getFreeSpace();
        long sdFreeSpaceL = Environment.getExternalStorageDirectory().getFreeSpace();
        String phoneFreeSpace = Formatter.formatFileSize(context, phoneFreeSpaceL);
        String sdFreeSpace = Formatter.formatFileSize(context, sdFreeSpaceL);
        tvPhoneSize.setText("手机剩余：" + phoneFreeSpace);
        tvSdSize.setText("sd卡剩余：" + sdFreeSpace);
    }

    public void getAppsList() {
        PackageManager pm = getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);//直接写也可以PackageManager.GET_INSTRUMENTATION
        for (PackageInfo packageInfo : packages) {
            ApplicationInfo info = packageInfo.applicationInfo;
            Drawable icon = info.loadIcon(pm);
            String label = info.loadLabel(pm).toString();
            String sourceDir = info.sourceDir;
            String packageName = packageInfo.packageName;
            /**
             * String name = info.name;//null
             * sourceDir=/data/app/so.ofo.labofo-1/base.apk
             * label=ofo共享单车
             * packageName=so.ofo.labofo
             */
            //            LogUtil.d("sourceDir=" + sourceDir + ",label=" + label + ",packageName=" + packageName);


            AppInfo appInfo = new AppInfo();
            appInfo.setLabel(label);
            appInfo.setSourceDir(sourceDir);
            appInfo.setIcon(icon);
            appInfo.setPackageName(packageName);

            File apkFile = new File(sourceDir);
            appInfo.setSize(apkFile.length());

            if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                appInfo.setSys(true);
            } else {
                appInfo.setSys(false);
            }

            if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE) {
                appInfo.setInPhone(false);
            } else {
                appInfo.setInPhone(true);
            }
            appList.add(appInfo);
        }
    }
}
